<template>
  <div class="panel">
    <el-button @click="addItem">新增</el-button>
    <el-input v-model="itemvalue" placeholder="请填写内容"></el-input>
  </div>

  <div class="parent">
    <template v-for="item in list" :key="item.id">
      <children
        @delete-item="deleteItem"
        @edit-item="editItem"
        :item="item"
      ></children>
    </template>
  </div>
  <div class="parent-1">
    <template v-for="(item, index) in historylog">
      <p>{{ index+1 }}.{{ item.time }}执行了{{ item.name }}</p>
    </template>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import Children from "./children.vue";
import { ElMessage } from "element-plus";
import dayjs from 'dayjs'
import { todoList } from '@/pinia/todolist.js'



let historylog = ref([]);
let data = reactive({
  list: [
    {
      name: "测试",
      id: Math.random(),
    },
  ],
});

const store = todoList()
// 监听变化与watch相比，发生变化执行一次
store.$subscribe((mutation, state) => {
 console.log('store发生了改变'+JSON.stringify(state))
})
let list = ref([]);

list.value = store.todoList

let itemvalue = ref();
const addItem = () => {
  if (!itemvalue.value) {
    ElMessage({
      showClose: true,
      message: "请填写内容",
      type: "error",
    });
    return;
  }
  // list.value.push({
  //   name: itemvalue.value,
  //   id: Math.random(),
  // });
  store.add({
    name: itemvalue.value,
    id: Math.random(),
  })
  itemvalue.value = "";
  historylog.value.push({
    time: dayjs().format('YYYY年MM月DD日 HH时mm分mm秒'),
    name: "添加",
  });
};
const editItem = (val, text) => {
  let index = list.value.findIndex((item) => item.id == val.id);
  if (index > -1) {
    list.value[index].name = text;
  }
  historylog.value.push({
    time: dayjs().format('YYYY年MM月DD日 HH时mm分mm秒'),
    name: "编辑",
  });
};
const deleteItem = (val) => {
  let index = list.value.findIndex((item) => item.id == val.id);
  if (index > -1) {
    store.deleted(val)
    // list.value.splice(index, 1);
    historylog.value.push({
      time: dayjs().format('YYYY年MM月DD日 HH时mm分mm秒'),
      name: "删除",
    });
  }
};
</script>
<style lang="scss">
.panel
{
  width: 500px;
}
.parent
  {
  width: 500px;
  min-height: 600px;
  box-shadow: 0px 0px 1px 1px #ccc;
  margin: 20px auot;
}
.parent-1
  {
  position: absolute;
  right: 0;
  top: 0;
  width: 500px;
  min-height: 600px;
  box-shadow: 0px 0px 1px 1px #ccc;
}
</style>
